package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //模糊查询
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(pageInfo, lqw);
        //要返回的结果，包含分类名称
        Page<DishDto> resultPage = new Page<>();
        //把pageInfo中的数据拷贝到resultPage中
        BeanUtils.copyProperties(pageInfo, resultPage, "records");

        //从数据库中查询到的集合，不包含分类名称
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> resultList = new ArrayList<>();

        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            //设置分类名称
            Category category = categoryService.getById(record.getCategoryId());
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }
            resultList.add(dishDto);
        }
        resultPage.setRecords(resultList);

        return R.success(resultPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        //根据分类id精确查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //根据售卖状态查询（查询启售状态）
        lqw.eq(Dish::getStatus, 1);
        //排序，根据sort正序排序，再根据修改时间倒叙排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(lqw);

        List<DishDto> resultList = list.stream().map(dishItem -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishItem, dishDto);
            //查询菜品的口味
            //select * from dish_flavor where dish_id=1397851668262465537
            LambdaQueryWrapper<DishFlavor> flavorLqw = new LambdaQueryWrapper<>();
            flavorLqw.eq(DishFlavor::getDishId, dishItem.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorLqw);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(resultList);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        dishService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 修改菜品状态,起售和停售
     *
     * @param ids
     */
    @PostMapping("/status/{statusId}")
    public R<String> status(@RequestParam List<Long> ids, @PathVariable int statusId) {
        dishService.statusWithSetmeal(ids,statusId);
        return R.success("菜品状态修改成功");
    }
}